<template>
  <div class="app-container">
    <div class="map" id="mapcontainer"></div>
    <div class="menu">
      <a-radio-group v-model:value="checked" button-style="solid" @change="checkedChange">
        <a-radio-button value="标记点">标记点</a-radio-button>
        <a-radio-button value="标记线">标记线</a-radio-button>
        <a-radio-button value="标记面">标记面</a-radio-button>
        <a-radio-button value="河流效果">河流效果</a-radio-button>
      </a-radio-group>
    </div>
  </div>
</template>
<script setup lang="ts">
import mapboxgl from "mapbox-gl/dist/mapbox-gl.js";
import "mapbox-gl/dist/mapbox-gl.css";
import {onMounted, ref} from "vue";
import {getGeoJson, getImage} from "./utils/tool.ts";
import CQQXJSON from "./assets/data/xzqh.json"
import HLZXXJSON from "./assets/data/HLZXX50_JSON.json"
import CQBJJSON from "./assets/data/cqbj.json"
import axios from "axios";
import {GeoJSONFeature} from "highcharts";
import {Feature} from "geojson"


let map: any = ref({});
let checked = ref('');
let markers = ref<any[]>([]);
let stationList = ref<any[]>([
  {name: '测站A', longitude: 105.84294965174374, latitude: 28.940978753912187},
  {name: '测站B', longitude: 105.92910321318035, latitude: 29.057478131732111},
  {name: '测站C', longitude: 106.14011892750005, latitude: 29.093222018000063},
  {name: '测站D', longitude: 106.19618672700005, latitude: 29.221070927500051},
  {name: '测站E', longitude: 106.27755542150007, latitude: 29.287121406500034},
  {name: '测站F', longitude: 106.39250547300009, latitude: 29.342951779000032},
  {name: '测站G', longitude: 106.49721232850007, latitude: 29.442807632500063},
  {name: '测站H', longitude: 106.53143395799751, latitude: 29.5388947145671},
  {name: '测站I', longitude: 106.62878197246209, latitude: 29.597188875423907},
  {name: '测站J', longitude: 106.78857546050006, latitude: 29.607925339500042},
  {name: '测站K', longitude: 106.90750620460256, latitude: 29.684980698524033},
  {name: '测站M', longitude: 107.04575396666615, latitude: 29.808513795975742},
  {name: '测站N', longitude: 107.292828722686, latitude: 29.725102748471908},
  {name: '测站O', longitude: 107.4740695748776, latitude: 29.813101933843811},
  {name: '测站P', longitude: 107.59157259309796, latitude: 29.83823350048435},
  {name: '测站Q', longitude: 107.85773915209421, latitude: 30.05915895139713},
  {name: '测站R', longitude: 108.00040121026612, latitude: 30.216712240549889},
  {name: '测站S', longitude: 108.12104574850008, latitude: 30.319891592500056},
  {name: '测站T', longitude: 108.18894938200006, latitude: 30.414331270000048},
  {name: '测站U', longitude: 108.29734001214368, latitude: 30.55641938370416},
  {name: '测站V', longitude: 108.52772763621161, latitude: 30.912066299521719},
  {name: '测站W', longitude: 108.54730588850006, latitude: 30.915175686000055},
  {name: '测站X', longitude: 108.88880195200005, latitude: 30.955506387500066},
  {name: '测站Y', longitude: 109.35629093153581, latitude: 30.973906589502327},
  {name: '测站Z', longitude: 109.65033379479894, latitude: 31.00701298037054},
]);
let hoveredQxStateId = ref();
let hoveredHlStateId = ref();

function initMap() {
  mapboxgl.accessToken = "pk.eyJ1IjoiZ2RiOGo2bHBrZSIsImEiOiJjbHNiY2dwbTMwY3pkMmpudDlidjhoOHN2In0.OoTvW_JCUbM2w9jZNdbKkw";
  map.value = new mapboxgl.Map({
    container: 'mapcontainer',
    center: [108.242, 30.264],//地图中心点
    style: {
      version: 8,
      name: 'custom',
      sprite: location.origin + '/mapbox/flSprite/sprite',
      glyphs: location.origin + '/mapbox/glyphs/fonts/{fontstack}/{range}.pbf',
      layers: [
        {
          id: 'background',
          type: 'background',
          paint: {
            "background-color": "#000",
          }
        }
      ],
      sources: {},
    },
    zoom: 7,
    maxZoom: 18,
    minZoom: 3.2,
    preserveDrawingBuffer: true,
  });
  map.value.on('load', () => {
    // map.value._logoControl && map.value.removeControl(map.value._logoControl);//去除mapbox图标
    //加载高德地图矢量图层
    // let gaodeTileURL = 'https://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}';//高德矢量图层
    // map.value.addSource('gaode-source', {
    //   'type': 'raster',
    //   'tiles': [gaodeTileURL],
    //   'tileSize': 256
    // });
    // map.value.addLayer({
    //   'id': 'gaode-layer',
    //   'type': 'raster',
    //   'source': 'gaode-source',
    //   'minzoom': 0,
    //   'maxzoom': 22
    // });
    //加载高德地图影像图层
    // let gaodeImgURL = 'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}';//高德影像图层
    // map.value.addSource('gaode-img-source', {
    //   'type': 'raster',
    //   'tiles': [gaodeImgURL],
    //   'tileSize': 256
    // });
    // map.value.addLayer({
    //   'id': 'gaode-img-layer',
    //   'type': 'raster',
    //   'source': 'gaode-img-source',
    //   'minzoom': 0,
    //   'maxzoom': 22
    // });
    // //加载高德地图标记图层
    // let gaodeMarkURL = 'https://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}';//高德标记图层
    // map.value.addSource('gaode-mark-source', {
    //   'type': 'raster',
    //   'tiles': [gaodeMarkURL],
    //   'tileSize': 256
    // });
    // map.value.addLayer({
    //   'id': 'gaode-mark-layer',
    //   'type': 'raster',
    //   'source': 'gaode-mark-source',
    //   'minzoom': 0,
    //   'maxzoom': 22
    // });
    const images: string[] = ['wz', 'wz2','station_ico'];
    images.forEach(imageName => {
      const url = getImage(`images/${imageName}.png`);
      map.value.loadImage(url, (error: any, image: any) => {
        if (error) throw error;
        //向地图注册图标
        map.value.addImage(imageName, image);
      })
    });
    // map.value.addLayer({
    //   'id': `mark-icon`,
    //   'type': 'symbol',
    //   'source': {
    //     'type': 'geojson',
    //     'data': {
    //       'type': 'FeatureCollection',
    //       'features': [],
    //     }
    //   },
    //   'layout': {
    //     'icon-image': 'wz',
    //     'icon-size': 0.6 // 图标大小
    //   }
    // });

    // 添加行政区边界图层
    // console.log("重庆边界数据>>",CQBJJSON)
    map.value.addSource('cq-bound-source', {
      type: 'geojson',
      data: CQBJJSON,
    });
    map.value.addLayer({
      id: 'cq-bound-layer',
      type: 'line',
      source: 'cq-bound-source',
      paint: {
        'line-color': '#084594',
        'line-width': 5
      }
    });
    // 添加区县GeoJSON数据源
    map.value.addSource('qx-source', {
      type: 'geojson',
      data: CQQXJSON
    });
    // // 添加区县图层
    map.value.addLayer({
      'id': 'cqqx-layer',
      'type': 'fill',
      'source': 'qx-source',
      'layout': {},
      'paint': {
        // 'fill-color': ['case', ['boolean', ['feature-state', 'bright'], false], '#d556ff', '#088'], // 区划颜色
        // 'fill-opacity': ['case', ['boolean', ['feature-state', 'bright'], false], 0, 0.5] // 区划透明度
        'fill-color': ['case', ['boolean', ['feature-state', 'hover'], false], '#0036c0', '#088'],
        'fill-opacity': 0.8,
      }
    });
    // // 添加一个图层来展示区县名称
    map.value.addLayer({
      id: 'qx-label-layer',
      type: 'symbol',
      source: 'qx-source',
      paint: {
        'text-color': '#FFF',
        // 'text-halo-color': '#2b3883',
        // 'text-halo-width': 1,
      },
      layout: {
        visibility: 'visible',
        'text-field': '{MC}',
        // 'text-font': ['微软雅黑 Regular'],
        'text-size': 12,
      },
      filter: [
        'in', ['get', 'SSQXBM'], ['literal', []]
      ]
    });
    let filterSet = new Set([]);
    CQQXJSON.features.forEach(it => {
      filterSet.add(it.properties.SSQXBM);
    });
    map.value.setFilter('qx-label-layer', ['all', ['>', ['zoom'], 5], ['in', ['get', 'SSQXBM'], ['literal', Array.from(filterSet)]]]);
    map.value.on('mousemove', 'cqqx-layer', function (e: any) {
      if (hoveredQxStateId.value) {
        map.value.setFeatureState(
            {source: 'qx-source', id: hoveredQxStateId.value},
            {hover: false}
        );
      }
      if (e.features[0].id) {
        map.value.getCanvas().style.cursor = 'pointer';
        hoveredQxStateId.value = e.features[0].id;
        map.value.setFeatureState(
            {source: 'qx-source', id: e.features[0].id},
            {hover: true});
      }
    });
    map.value.on('mouseleave', 'cqqx-layer', function () {
      if (hoveredQxStateId.value) {
        map.value.getCanvas().style.cursor = 'inherit';
        map.value.setFeatureState(
            {source: 'qx-source', id: hoveredQxStateId.value},
            {hover: false}
        );
        hoveredQxStateId.value = '';
      }
    });
  });
}

onMounted(() => {
  initMap();
})

function checkedChange() {
  removeLayer();
  map.value.off('click', onMapClick);
  map.value.easeTo({
    center: [108.242, 30.264],
    zoom: 7,
    duration: 2000,
  });
  if (checked.value == '河流效果') {
    riverFlow();
  } else {
    map.value.on('click', onMapClick);
  }
}

function onMapClick(e: any) {
  switch (checked.value) {
    case '标记点':

      // let times = new Date().getTime();
      // map.value.addLayer({
      //   'id': `mark-icon-${times}`,
      //   'type': 'symbol',
      //   'source': {
      //     'type': 'geojson',
      //     'data': {
      //       'type': 'FeatureCollection',
      //       'features': [
      //         {
      //           'type': 'Feature',
      //           'geometry': {
      //             'type': 'Point',
      //             'coordinates': [e.lngLat.lng, e.lngLat.lat] // 标记点的坐标
      //           }
      //         }
      //       ]
      //     }
      //   },
      //   'layout': {
      //     'icon-image': 'wz',
      //     'icon-size': 0.6 // 图标大小
      //   }
      // });
      // map.value.on('mouseenter', `mark-icon-${times}`, function(e:any) {
      //   console.log("鼠标移入>>",e)
      // });
      // map.value.on('mouseleave', `mark-icon-${times}`, function(e:any) {
      //   console.log("鼠标移出>>",e)
      // });

      // // 添加标记到自定义图层
      // let geojson = {
      //   'type': 'Feature',
      //   'geometry': {
      //     'type': 'Point',
      //     'coordinates': [e.lngLat.lng, e.lngLat.lat] // 标记点的坐标
      //   }
      // }
      // // 获取源数据引用
      // let source = map.value.getSource('mark-icon');
      // // 更新源数据添加新的标记
      // source.setData(geojson);

      let el = document.createElement('div')
      el.id = 'markerId'
      // el.style.backgroundColor = '#1546b2'
      el.style.backgroundImage = `url(${getImage('images/wz.png')})`;
      el.style.backgroundSize = '100% 100%'
      el.style.width = 30 + 'px';
      el.style.height = 30 + 'px';
      // el.style.borderRadius = '50%';
      // 添加弹窗
      let popup = new mapboxgl.Popup({offset: 25}).setHTML(`标记点坐标${[Number(e.lngLat.lng).toFixed(3), Number(e.lngLat.lat).toFixed(3)]}`);
      let marker = new mapboxgl.Marker(el)
          .setLngLat(e.lngLat)
          .setPopup(popup);
      markers.value.push(marker);
      marker.addTo(map.value);
      break;
    case '标记线':
      removeLayer();
      // 线的数据
      let geojson = {
        type: 'FeatureCollection',
        features: [
          {
            type: 'Feature',
            properties: {},
            geometry: {
              type: 'LineString',
              coordinates: [
                [e.lngLat.lng, e.lngLat.lat],
                [Number(e.lngLat.lng) + 1, Number(e.lngLat.lat) - 1]
              ]
            }
          }
        ]
      };
      map.value.addSource('line-source', {
        type: 'geojson',
        data: geojson
      });
      map.value.addLayer({
        id: 'line-layer',
        type: 'line',
        source: 'line-source',
        layout: {
          'line-join': 'round',
          'line-cap': 'round'
        },
        paint: {
          'line-color': '#3887d4',
          'line-width': 5
        }
      });
      break;
    case '标记面':
      removeLayer();
      // 面的坐标数组，表示为一个多边形
      let coordinates = [
        [
          [e.lngLat.lng, e.lngLat.lat], // 多边形的一个点
          [Number(e.lngLat.lng) + 0.1, Number(e.lngLat.lat) - 0.1],
          [Number(e.lngLat.lng) + 0.5, Number(e.lngLat.lat) - 0.45],
          [Number(e.lngLat.lng) + 1.2, Number(e.lngLat.lat) + 0.6],
          [Number(e.lngLat.lng) + 1.45, Number(e.lngLat.lat) + 1.83],
          [e.lngLat.lng, e.lngLat.lat], // 首尾点相连形成闭环
        ]
      ];
      // 添加面图层
      map.value.addLayer({
        'id': 'polygon-layer',
        'type': 'fill',
        'source': {
          'type': 'geojson',
          'data': {
            'type': 'Feature',
            'properties': {},
            'geometry': {
              'type': 'Polygon',
              'coordinates': coordinates
            }
          }
        },
        'layout': {},
        'paint': {
          'fill-color': '#0080ff', // 填充颜色
          'fill-opacity': 0.5 // 填充透明度
        }
      });
      break;
      // case '河流效果':
      //   const featureList: Feature[] = []
      //   HLZXXJSON.features.map((feature: GeoJSONFeature) => {
      //     const {attributes, geometry} = feature as any
      //     attributes.id = attributes.FID;
      //     const temp: Feature = {
      //       type: 'Feature',
      //       id: attributes.FID,
      //       properties: {...attributes},
      //       geometry: {
      //         coordinates: geometry.coordinates || geometry.paths[0],
      //         type: 'LineString',
      //       }
      //     };
      //     featureList.push(temp);
      //   });
      //   // 添加河流中心线GeoJSON数据源
      //   map.value.addSource('hlzxx-source', {
      //     type: 'geojson',
      //     data: {
      //       type: 'FeatureCollection',
      //       features: featureList,
      //     },
      //   });
      //   map.value.addLayer({
      //     id: 'hlzxxLayer',
      //     type: 'line',
      //     source: 'hlzxx-source',
      //     minzoom: 5,
      //     layout: {
      //       'line-join': 'round',
      //       'line-cap': 'round',
      //       visibility: 'visible',
      //     },
      //     paint: {
      //       'line-color': [
      //         'case',
      //         ['boolean', ['feature-state', 'hover'], false],
      //         '#59ED7F',
      //         ['boolean', ['feature-state', 'bright'], false],
      //         '#161ef8',
      //         '#63bce3',
      //       ],
      //       'line-width': ['case', ['all', ['!=', '长江', ['get', 'MC']]], 4, 8],
      //       'line-opacity': [
      //         'case',
      //         ['boolean', ['feature-state', 'hover'], false],
      //         1,
      //         ['boolean', ['feature-state', 'bright'], false],
      //         1,
      //         ['all', ['!=', '长江', ['get', 'MC']]],
      //         0.2,
      //         1,
      //       ],
      //     },
      //     filter: ['all', ['!=', ' ', ['get', 'MC']]],
      //   });
      //   break;
  }

}

//河流效果
function riverFlow() {
  const featureList: Feature[] = []
  HLZXXJSON.features.map((feature: GeoJSONFeature) => {
    const {attributes, geometry} = feature as any
    attributes.id = attributes.FID;
    const temp: Feature = {
      type: 'Feature',
      id: attributes.FID,
      properties: {...attributes},
      geometry: {
        coordinates: geometry.coordinates || geometry.paths[0],
        type: 'LineString',
      }
    };
    featureList.push(temp);
  });
  // 添加河流中心线GeoJSON数据源
  map.value.addSource('hlzxx-source', {
    type: 'geojson',
    data: {
      type: 'FeatureCollection',
      features: featureList,
    },
  });
  map.value.addLayer({
    id: 'hlzxx-layer',
    type: 'line',
    source: 'hlzxx-source',
    minzoom: 5,
    layout: {
      'line-join': 'round',
      'line-cap': 'round',
      visibility: 'visible',
    },
    paint: {
      'line-color': [
        'case',
        ['boolean', ['feature-state', 'hover'], false],
        '#59ED7F',
        ['boolean', ['feature-state', 'bright'], false],
        '#161ef8',
        '#63bce3',
      ],
      'line-width': ['case', ['all', ['!=', '长江', ['get', 'MC']]], 4, 8],
      'line-opacity': [
        'case',
        ['boolean', ['feature-state', 'hover'], false],
        1,
        ['boolean', ['feature-state', 'bright'], false],
        1,
        ['all', ['!=', '长江', ['get', 'MC']]],
        0.2,
        1,
      ],
    },
    filter: ['all', ['!=', ' ', ['get', 'MC']]],
  });
  map.value.on('mousemove', 'hlzxx-layer', function (e: any) {
    if (hoveredHlStateId.value) {
      map.value.setFeatureState(
          {source: 'hlzxx-source', id: hoveredHlStateId.value},
          {hover: false}
      );
    }
    if (e.features[0].id) {
      map.value.getCanvas().style.cursor = 'pointer';
      hoveredHlStateId.value = e.features[0].id;
      map.value.setFeatureState(
          {source: 'hlzxx-source', id: e.features[0].id},
          {hover: true});
    }
  });
  map.value.on('mouseleave', 'hlzxx-layer', function () {
    if (hoveredHlStateId.value) {
      map.value.getCanvas().style.cursor = 'inherit';
      map.value.setFeatureState(
          {source: 'hlzxx-source', id: hoveredHlStateId.value},
          {hover: false}
      );
      hoveredHlStateId.value = '';
    }
  });
  //添加站点图层
  const stationFeatureList = stationList.value.map(it => {
    return {
      type: 'Feature',
      geometry: {
        coordinates: [Number(it.longitude), Number(it.latitude)],
        type: 'Point',
      },
      properties: {...it},
    }
  });
  map.value.addSource('station-source', {
    type: 'geojson',
    data: {
      type: 'FeatureCollection',
      features: stationFeatureList as Feature[],
    }
  });
  map.value.addLayer({
    id: 'station-layer',
    type: 'symbol',
    source: 'station-source',
    minzoom: 5,
    paint: {
      'text-color': 'red',
      'text-halo-color': '#fff',
      'text-halo-width': 2,
    },
    layout: {
      // 'text-field': ['case', ['get', 'name'], ''],
      'text-font': ['微软雅黑 Regular'],
      'icon-offset': [0, -30],
      'icon-image': 'station_ico',
      'icon-size': 0.8,
      'icon-ignore-placement': true,
      'text-ignore-placement': true,
      'text-allow-overlap': true,
      'icon-allow-overlap': true,
    },
  });
  map.value.easeTo({
    center: [Number(stationList.value[0].longitude), Number(stationList.value[0].latitude)],
    zoom: 9,
    duration: 2000,
  });



}

//移除图层
function removeLayer() {
  let style = map.value.getStyle()
  style.layers.forEach(function (layer: any) {
    console.log("layer>>", layer)
    if (layer.id.includes('mark-icon')) {//移除图标图层
      map.value.getLayer(layer.id) && map.value.removeLayer(layer.id);
    }
    if (layer.id.includes('line-layer')) {//移除线图层
      map.value.getLayer(layer.id) && map.value.removeLayer(layer.id);
      map.value.getSource(layer.source) && map.value.removeSource(layer.source);
    }
    if (layer.id.includes('polygon')) {//移除面图层
      map.value.getLayer(layer.id) && map.value.removeLayer(layer.id);
      map.value.getSource(layer.source) && map.value.removeSource(layer.source);
    }
    if (layer.id.includes('hlzxx')) {
      map.value.getLayer(layer.id) && map.value.removeLayer(layer.id);
      map.value.getSource(layer.source) && map.value.removeSource(layer.source);
    }
    if (layer.id.includes('station')) {
      map.value.getLayer(layer.id) && map.value.removeLayer(layer.id);
      map.value.getSource(layer.source) && map.value.removeSource(layer.source);
    }
  });
  map.value.getLayer('station-layer') && map.value.removeLayer('station-layer');
  map.value.getSource('station-source') && map.value.removeSource('station-source');
  markers.value.forEach((marker: any) => {
    marker.remove();
  });

}
</script>
<style scoped>
.app-container {
  width: 100%;
  height: 96vh;
  position: relative;

  .map {
    width: 100%;
    height: 100%;
  }

  .menu {
    position: absolute;
    top: 10px;
    left: 10px;
  }
}
</style>
